﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Utility.Helper
{
    public static class AutoMapperExtension
    {
  
        public static T MapTo<T>(this object source)
        {

            Type sourceType = source.GetType();
            Type destinationType = typeof(T);

            if (sourceType.IsGenericType)
                sourceType = sourceType.GenericTypeArguments[0];

            if (destinationType.IsGenericType)
                destinationType = destinationType.GenericTypeArguments[0];

            MapperConfiguration config = new MapperConfiguration(ctx => ctx.CreateMap(sourceType, destinationType));
            IMapper mapper = config.CreateMapper();

            return mapper.Map<T>(source);
        }


        public static T Map<T>(this object source, T target)
        {
            Type sourceType = source.GetType();
            Type destinationType = typeof(T);

            if (sourceType.IsGenericType)
                sourceType = sourceType.GenericTypeArguments[0];

            if (destinationType.IsGenericType)
                destinationType = destinationType.GenericTypeArguments[0];

            MapperConfiguration config = new MapperConfiguration(ctx => ctx.CreateMap(sourceType, destinationType));
            IMapper mapper = config.CreateMapper();
            T newModel = mapper.Map(source, target);

            return newModel;
        }
    }
}
